package com.example.frame_java.utlis;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;


import com.bumptech.glide.Glide;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;


import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhtttpUtlis {
    public static String GET = "GET";
    public static String POST = "POST";
    public static String PUT = "PUT";
    public static String token;
    public static String URL = "http://124.93.196.45:10001";
    public static OkHttpClient okHttpClient;
    public static Handler handler;
    public static Gson gson;
    public static String TAG = "TAG";
    private static ViewPager vp;
    private static SharedPreferences sharedPreferences;

    public static void init() {
        gson = new Gson();
        handler = new Handler();
        okHttpClient = new OkHttpClient();
    }

    public static void doRequst(String url, String method, Class clazz, Netword netword, String... json) {
        try {
            Request build = null;
            if (gson == null || handler == null || okHttpClient == null) {
                init();
            }
            Request.Builder builder = new Request.Builder();

            if (!TextUtils.isEmpty(url)) {
                url = URL + url;
                builder.url(url);
                Log.e(TAG, "URL=" + url);
            }

            if (!TextUtils.isEmpty(token)) {
                builder.addHeader("Authorization", token);
                Log.e(TAG, "token=" + token);
            }

            if (GET.equals(method)) {
                builder.get();
            } else if (POST.equals(method) && json.length > 0) {
                builder.put(RequestBody.create(MediaType.parse("application/json"), json[0]));
            } else if (PUT.equals(method) && json.length > 0) {
                builder.put(RequestBody.create(MediaType.parse("application/json"), json[0]));
            }
            build = builder.build();

            okHttpClient.newCall(build).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    netword.no(e.getMessage());
                    Log.e(TAG, "请求失败=" + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String string = response.body().string();
                    Log.e(TAG, "JSON==" + string);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Object obj = gson.fromJson(string, clazz);
                            netword.ok(obj);
                        }
                    });
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "解析错误==" + e.getMessage());
        }
    }

    public interface Netword {
        public void ok(Object obj);

        public void no(String mas);
    }

    public static void dologin(View view, String text, String but, View.OnClickListener onClickListener) {
       if(OkhtttpUtlis.token==null){
           Snackbar.make(view, text, Snackbar.LENGTH_SHORT).setAction(but, new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   onClickListener.onClick(v);
               }
           }).show();
       }
    }

    private static void getSharedPreferences(Context context) {
        sharedPreferences = context.getSharedPreferences("login", Context.MODE_PRIVATE);
    }

    public static String get(Context context, String key) {
        if (sharedPreferences == null) {
            getSharedPreferences(context);
        }
        return sharedPreferences.getString(key, "");
    }

    public static void set(String key, String value, Context context) {
        if (sharedPreferences == null) {
            getSharedPreferences(context);
        }
        sharedPreferences.edit().putString(key, value).apply();
    }


    public static void doCarouselMap(ViewPager viewPager, Context context, List<String> list) {
        try {
            vp = viewPager;
            Pages pages = new Pages(context, list);
            vp.setAdapter(pages);
            mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
        } catch (Exception e) {
            Log.e(TAG, "轮播图解析错误" + e.getMessage());
        }
    }

    public static class Pages extends PagerAdapter {

        public Context context;
        public List<String> list;

        public Pages(Context context, List<String> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }


        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView imageView = null;
            try {
                imageView = new ImageView(context);
                Glide.with(context).load(URL + list.get(position)).into(imageView);
                container.addView(imageView);
            } catch (Exception e) {
                Log.e(TAG, "照片解析错误" + e.getMessage());
            }
            return imageView;
        }
    }

    public static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            try {
                if (msg.what == 0 && vp != null) {
                    int currentItem = vp.getCurrentItem();
                    currentItem = (currentItem + 1) % 3;
                    vp.setCurrentItem(currentItem);
                    mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
                }
            } catch (Exception e) {
                Log.e(TAG, "mHandler" + e.getMessage());
            }
        }
    };


}
